package net.guerlab.smart.platform.user.web.controller.user;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.guerlab.sdk.dingtalk.client.DingTalkClient;
import net.guerlab.sdk.dingtalk.request.user.UserGetUserInfoRequest;
import net.guerlab.sdk.dingtalk.response.user.UserGetUserInfoResponse;
import net.guerlab.smart.platform.basic.auth.annotation.IgnoreLogin;
import net.guerlab.smart.platform.commons.exception.UnsupportedLoginModeException;
import net.guerlab.smart.platform.commons.exception.UserIdInvalidException;
import net.guerlab.smart.platform.user.web.controller.AbstractOauthControlPanelController;
import net.guerlab.smart.platform.user.web.domain.LoginResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 钉钉-控制面板
 *
 * @author guer
 */
@Api(tags = "钉钉-控制面板")
@RestController("/user/dingTalk/controlPanel")
@RequestMapping("/user/dingTalk/controlPanel")
public class DingTalkControlPanelController extends AbstractOauthControlPanelController {

    private DingTalkClient dingTalkClient;

    @Override
    protected String getOauthType() {
        return "DING_TALK";
    }

    @IgnoreLogin
    @ApiOperation("通过code登录")
    @GetMapping("/loginByCode")
    public LoginResponse loginByCode(@ApiParam(value = "code", required = true) @RequestParam String code,
            HttpServletRequest request) {
        UserGetUserInfoRequest userGetUserInfoRequest = new UserGetUserInfoRequest();
        userGetUserInfoRequest.setCode(code);

        UserGetUserInfoResponse response = getDingTalkClient().execute(userGetUserInfoRequest);

        String userId = response.getUserId();

        if (StringUtils.isBlank(userId)) {
            throw new UserIdInvalidException();
        }

        return getLoginSucceedDTO(findUser(userId), userId, request, getOauthType());
    }

    private DingTalkClient getDingTalkClient() {
        if (dingTalkClient == null) {
            throw new UnsupportedLoginModeException();
        }
        return dingTalkClient;
    }

    @Autowired(required = false)
    public void setDingTalkClient(DingTalkClient dingTalkClient) {
        this.dingTalkClient = dingTalkClient;
    }
}
